<?php
namespace Admin\Model;
use Think\Model;
class CategoryModel extends Model 
{
	protected $insertFields = array('cat_name','parent_id,if_floor');
	protected $updateFields = array('id','cat_name','parent_id,is_floor');
	protected $_validate = array(
		array('cat_name', 'require', '分类名称不能为空！', 1, 'regex', 3),
		array('cat_name', '1,30', '分类名称的值最长不能超过 30 个字符！', 1, 'length', 3),
		array('parent_id', 'number', ' 上级分类的Id,0:顶级分类必须是一个整数！', 2, 'regex', 3),
	);


	public function search($pageSize = 20)
	{
		/**************************************** 搜索 ****************************************/
		$where = array();
		if($cat_name = I('get.cat_name'))
			$where['cat_name'] = array('like', "%$cat_name%");
		if($parent_id = I('get.parent_id'))
			$where['parent_id'] = array('eq', $parent_id);
		/************************************* 翻页 ****************************************/
		$count = $this->alias('a')->where($where)->count();
		$page = new \Think\Page($count, $pageSize);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
		$data['page'] = $page->show();
		/************************************** 取数据 ******************************************/
		$data['data'] = $this->alias('a')->where($where)->group('a.id')->limit($page->firstRow.','.$page->listRows)->select();
		return $data;
	}
	// 添加前
	protected function _before_insert(&$data, $option)
	{
	}
	// 修改前
	protected function _before_update(&$data, $option)
	{
	}
	// 删除前
	protected function _before_delete($option)
	{
	    $children = $this->getChildren($option['where']['id']);
        if ($children){
            $children  = implode(',',$children);
            $model = new \Think\Model;
            $model->table('__CATEGORY__')->delete($children);
        }

		if(is_array($option['where']['id']))
		{
			$this->error = '不支持批量删除';
			return FALSE;
		}
	}
	/************************************ 其他方法 ********************************************/
    public function getChildren($catId){
        $data = $this->select();
        return $this->_getChildren($data,$catId,true);
    }

    private function _getChildren($data,$catId,$isClearId=false){
        static  $_ret = array();
        if ($isClearId)
            $_ret = array();
        foreach ($data as $k => $v){
            if ($v['parent_id'] == $catId){
                $_ret[] = $v['id'];
                $this->_getChildren($data,$v['id']);
            }
        }
        return $_ret;
    }

    public function getTree() {
        $data = $this->select();
        return $this->_getTree($data);
    }

    private function _getTree($data,$parent_id=0,$level=0){
        static $_ret = array();
        foreach ($data as $k => $v){
            if ($v['parent_id'] == $parent_id){
                $v['level'] = $level;
                $_ret[] = $v;
                $this->_getTree($data,$v['id'],$level+1);
            }
        }
        return $_ret;
    }

    public function getNavData() {
        //从缓存中取出catData数据
        $catData = S('catData');
        if (!$catData){
            $all = $this->select();
            $ret = array();
            foreach($all as $k => &$v) {
                if ($v['parent_id'] == 0 ){
                    foreach($all as $k1 => &$v1) {
                        if ($v1['parent_id'] == $v['id']) {
                            foreach ($all as $k2 =>$v2){
                                if ($v2['parent_id'] == $v1['id']) {
                                    $v1['children'][] = $v2;
                                }
                            }
                            $v['children'][] = $v1;
                        }
                    }
                    $ret[] = $v;
                }
            }
            //把数组缓存一天
            //S('catData',$ret,86400);
            $ret = array_slice($ret, 0, 13);
            return $ret;
        } else {
          return  $catData;
        }
    }

    public function floorData() {
        $floorData = S('floorData');
        if (!$floorData)
        {
            //取出推荐楼层的顶层分类
            $ret = $this->where(array(
                'parent_id' =>array('eq',0),
                'is_floor' => array('eq','是'),
            ))->select();

            $goodsModel = D('Admin/Goods');
            foreach ($ret as $k => $v) {
                //循环每个楼层取出楼层中的数据
                $goodsId = $goodsModel->getGoodsIdByCatId($v['id']);

                !$goodsId && $goodsId = array(0);

                $ret[$k]['brand'] = $goodsModel->alias('a')
                    ->join('LEFT JOIN __BRAND__ b on a.brand_id=b.id')
                    ->field('DISTINCT a.brand_id,b.brand_name,b.logo')
                    ->where(array(
                        'a.id' => array('in',$goodsId),
                        'a.brand_id' =>array('neq',0),
                    ))->limit(9)->select();
                //子分类
                $ret[$k]['subCat'] = $this->where(array(
                    'parent_id' => array('eq',$v['id']),
                    'is_floor' => array('eq','否'),
                ))->select();

                //上到楼层的商品
                $ret[$k]['recSubCat'] = $this->where(array(
                    'parent_id' => array('eq',$v['id']),
                    'is_floor' => array('eq','是'),
                ))->select();

                //循环每个推荐的二级分类下的8件被推荐到楼层的商品
                foreach ($ret[$k]['recSubCat'] as $k1 => &$v1) {
                    //取出这个分类下所有商品的id并返回一维数组
                    $gids = $goodsModel->getGoodsIdByCatId($v1['id']);
                    !$gids && $gids = array(0);
                    //再把根据商品id取出商品的详细信息
                    $v1['goods'] = $goodsModel->field('id,mid_logo,goods_name,shop_price')->where(array(
                        'is_on_sale' => array('eq','是'),
                        'is_floor' => array('eq','是'),
                        'id' => array('in',$gids),
                    ))->order('sort_num ASC')->limit(8)->select();
                }
            }
            //S('floorData',$ret,86400);
            $ret = array_slice($ret,0,13);
            return $ret;
        } else {
            return $floorData;
        }
    }

    public function parentPath($catId){
        static $ret = array();
        $info = $this->field('id,cat_name,parent_id')->find($catId);
        $ret[] = $info;
        if ($info['parent_id'] > 0)
            $this->parentPath($info['parent_id']);
        return $ret;
    }

    public function getSearchConditionByGoodsId($goodsId){

        $ret = array();//返回的数组

        $goodsModel = D('Admin/Goods');
        //这个分类下的商品id
        //$goodsId = $goodsModel->getGoodsIdByCatId($goodsId);
        !$goodsId && $goodsId = array(0);
        /********************品牌*********************/
        //根据商品id取出品牌ID再连品牌表取出品牌名称
        $ret['brand'] = $goodsModel->alias('a')
            ->field('DISTINCT a.brand_id,b.brand_name,b.logo')
            ->join('LEFT JOIN __BRAND__ b on a.brand_id=b.id')
            ->where(array(
                'a.id' => array('in',$goodsId),
                'a.brand_id' => array('neq',0),
            ))->select();

        //价格区间
        $sectionCount = 6;//默认分段
        $priceInfo = $goodsModel->field('MAX(shop_price) max_price,MIN(shop_price) min_price')
            ->where(array(
                'id' => array('in',$goodsId),
            ))->find();

        //最大价和最小价的区间
        $priceSection = $priceInfo['max_price'] - $priceInfo['min_price'];
        $goodsCount = count($goodsId);//分类下的商品数
        if ($goodsCount > 1){
            if ($priceSection < 100)
                $sectionCount = 2;
            elseif ($priceSection < 1000)
                $sectionCount = 4;
            elseif ($priceSection < 10000)
                $sectionCount = 6;
            else
                $sectionCount = 7;

            //根据这个段数分段
            $pricePerSection = ceil($priceSection/$sectionCount);
            $price = array();
            $firstPrice = 1199;
            for ($i = 0; $i < $sectionCount; $i++){
                //每段数结束的价格
                $_tmpEnd = $firstPrice+ $pricePerSection;
                //调整结束的价格
                $_tmpEnd = ((ceil($_tmpEnd/100)) * 100 - 1);
                $price[] = $firstPrice.'-'.$_tmpEnd;
                $firstPrice = $_tmpEnd + 1;
            }
            $ret['price'] = $price;
        }
        /***********商品属性*********/
        $gaModel = D('Admin/Goods_attr');
        $gaData = $gaModel->alias('a')->field('DISTINCT a.attr_id,a.attr_value,b.attr_name')
            ->join('LEFT JOIN __ATTRIBUTE__ b on a.attr_id=b.id')
            ->where(array(
                'a.goods_id' => array('in',$goodsId),
                'a.attr_value' => array('neq',''),
            ))->select();
        //属性数组,属性相同的放到一起,用属性名称做下标,2维转三维
        $_gaData = array();
        foreach ($gaData as $k => $v){
            $_gaData[$v['attr_name']][] = $v;
        }
        $ret['gaData'] = $_gaData;
        return $ret;
    }
}